<script lang="jsx" setup>
import { ref, watch } from 'vue';
import { UUID } from 'uuidjs';
import { ElTree } from 'element-plus';
import {
  addCheckItem,
  getAllForms,
  getFormCheckItems,
  updateCheckItem,
  updateFormCheckItems
} from '@/service/api/modules/check-inventory-manage/form-setup';
import Add from './modules/add.vue';

// 左边
const treeRef = ref(null);
const leftData = ref([]);
const formName = ref(null);
const defaultProps = {
  children: 'children',
  label: 'label'
};

const searchParams = ref({
  delFlag: null
});

// 筛选节点
function filterNode(value, data) {
  if (!value) return true;
  return data.label.includes(value);
}

watch(
  () => formName.value,
  val => {
    treeRef.value.filter(val);
  }
);

const currentFormId = ref(null);
function handleNodeClick(node) {
  if (node.type === 'process') {
    window.$message.warning('请选择表单');
    return;
  }
  currentFormId.value = node.id;
  searchParams.value.delFlag = null;
  getRightData();
}

// 分类方法
function classification(list) {
  const data = list.reduce((acc, currentItem) => {
    // 获取当前项目的 inspectionProcessName
    const key = currentItem.inspectionProcessName;

    // 如果分类对象中还没有这个 key，初始化为一个空数组
    if (!acc[key]) {
      acc[key] = [];
    }

    // 将当前项目加入相应的分类数组中
    acc[key].push(currentItem);

    return acc;
  }, {});
  return Object.entries(data).map(([key, value]) => {
    return {
      label: key,
      id: UUID.genV4().hexNoDelim,
      type: 'process',
      children: value?.map(item => {
        return {
          ...item,
          label: item.inspectionFormName,
          type: 'form'
        };
      })
    };
  });
}

async function getLeftData() {
  const { data, error } = await getAllForms();
  if (!error) {
    leftData.value = classification(data);
  }
}

getLeftData();

const currentEditFormData = ref({});
const { handleClose, handleShow, handleLoading } = window.$useModal({
  modalOption: {
    title: '编辑表单',
    width: '800px',
    destroyOnClose: true
  },
  formData: currentEditFormData.value,
  formList: [
    {
      type: 'tabs',
      name: '基本信息',
      span: 24
    },
    {
      type: 'input',
      key: 'inspectionFormName',
      label: '表单名称',
      placeholder: '请输入表单名称',
      disabled: true,
      span: 24
    },
    {
      type: 'input',
      key: 'inspectionFormCode',
      label: '表单编号',
      placeholder: '请输入表单编号',
      span: 24,
      rule: {
        required: true,
        message: '请输入表单编号',
        trigger: 'change'
      }
    },
    {
      type: 'radio',
      key: 'delFlag',
      label: '状态',
      span: 24,
      value: '0',
      selectOptions: [
        {
          label: '启用',
          value: '0'
        },
        {
          label: '禁用',
          value: '1'
        }
      ]
    },

    {
      type: 'radio',
      key: 'hasIpqc',
      label: '是否有IPQC审核',
      span: 24,
      value: '0',
      selectOptions: [
        {
          label: '是',
          value: '0'
        },
        {
          label: '否',
          value: '1'
        }
      ]
    },
    {
      type: 'radio',
      key: 'hasFqa',
      label: '是否有FQA审核',
      span: 24,
      value: '1',
      selectOptions: [
        {
          label: '是',
          value: '0'
        },
        {
          label: '否',
          value: '1'
        }
      ]
    },
    {
      type: 'tabs',
      name: '状态信息',
      span: 24
    },
    {
      type: 'input',
      key: 'createBy',
      label: '创建人',
      disabled: true,
      span: 12
    },
    {
      type: 'input',
      key: 'createDate',
      label: '创建时间',
      disabled: true,
      span: 12
    },
    {
      type: 'input',
      key: 'updateBy',
      label: '修改人',
      disabled: true,
      span: 12
    },
    {
      type: 'input',
      key: 'updateDate',
      label: '修改时间',
      disabled: true,
      span: 12
    }
  ],
  onOk: async formData => {
    console.log(formData);
    handleLoading(true);
    try {
      const { error } = await updateFormCheckItems(formData);
      if (!error) {
        window.$message.success('修改成功');
        handleClose();
        getLeftData();
      }
    } finally {
      handleLoading(false);
    }
  }
});

function handleTreeItemEdit(e, data) {
  console.log(data);
  currentEditFormData.value = data;
  e.stopPropagation();
  handleShow(window.$utils.deepClone(data));
}

// 右边
const searchFormList = [
  {
    type: 'select',
    key: 'delFlag',
    label: '状态',
    placeholder: '请选择状态',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 6,
    selectOptions: [
      {
        label: '启用',
        value: '0'
      },
      {
        label: '禁用',
        value: '1'
      }
    ]
  }
];

const column = ref([
  {
    key: 'dataIndex',
    dataIndex: 'dataIndex',
    title: '序号',
    width: 70,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemProcess',
    dataIndex: 'itemProcess',
    title: '点检流程',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemName',
    dataIndex: 'itemName',
    title: '点检项目',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemStardard',
    dataIndex: 'itemStardard',
    title: '标准',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'itemFrequence',
    dataIndex: 'itemFrequence',
    title: '频率',
    width: 150,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'showNo',
    dataIndex: 'showNo',
    title: '顺序编号',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'delFlag',
    dataIndex: 'delFlag',
    title: '状态',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <span class={record.delFlag === '0' ? 'color-green' : 'color-red'}>{['启用', '禁用'][record.delFlag]}</span>
      );
    }
  },
  {
    key: 'createBy',
    dataIndex: 'createBy',
    title: '创建人',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    title: '修改时间',
    width: 180,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'updateBy',
    dataIndex: 'updateBy',
    title: '修改人',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'cz-Col',
    dataIndex: 'cz-Col',
    title: '操作',
    width: 130,
    align: 'center',
    fixed: 'right',
    checked: true,
    ellipsis: true,
    customRender: ({ record }) => {
      return (
        <div>
          <a
            v-hasAuth={[['check-inventory-manage:form-setup:edit-check-item']]}
            class="mr-10px color-blue"
            onClick={() => {
              handleCheckItemEdit('edit', record);
            }}
          >
            修改
          </a>
          <a
            v-hasAuth={[['check-inventory-manage:form-setup:change-check-item-status']]}
            class={record.delFlag === '0' ? 'color-red' : 'color-green'}
            onClick={() => {
              delCheckItem(record);
            }}
          >
            {['禁用', '启用'][record.delFlag]}
          </a>
        </div>
      );
    }
  }
]);
const tableData = ref([]);
const tableRef = ref(null);
const loading = ref(false);

async function getRightData() {
  loading.value = true;
  try {
    const { data, error } = await getFormCheckItems({ inspectionFormId: currentFormId.value, ...searchParams.value });
    if (!error) {
      data.forEach((item, index) => {
        item.dataIndex = index + 1;
      });
      tableData.value = data;
    }
  } finally {
    loading.value = false;
  }
}

function delCheckItem(item) {
  window.$modal.confirm({
    title: `是否${item.delFlag === '0' ? '禁用' : '启用'}名称为“${item.itemName}”的点检项？`,
    onOk: async () => {
      const params = { ...item };
      params.delFlag = item.delFlag === '0' ? '1' : '0';
      updateCheckItem(params).then(({ data, error }) => {
        if (!error) {
          window.$message.success('操作成功');
          getRightData();
        }
      });
    }
  });
}

const addRef = ref(null);
const operationType = ref('add');
const currentRow = ref(null);
const {
  handleShow: handleCheckItemShow,
  handleLoading: handleCheckItemLoading,
  updateModalOptions,
  handleClose: handleCheckItemClose
} = window.$useModal({
  modalOption: {
    title: `新增检查项`,
    height: '700px',
    destroyOnClose: true
  },
  component: () => <Add ref={addRef} row-data={currentRow.value}></Add>,
  onOk: async () => {
    const data = { ...addRef.value };
    await data.validateForm();
    try {
      const formData = { ...data.model };
      let pro;
      formData.showNo = Number(formData.showNo);
      formData.inspectionFormId = currentFormId.value;
      if (operationType.value === 'add') {
        pro = await addCheckItem(formData);
      } else {
        pro = await updateCheckItem({ ...currentRow.value, ...formData });
      }
      const { error } = await pro;
      if (!error) {
        window.$message.success('操作成功');
        handleCheckItemClose();
        getRightData();
      }
    } finally {
      handleCheckItemLoading(false);
    }
  }
});

// 修改检查项
function handleCheckItemEdit(type, row) {
  operationType.value = type;

  if (type === 'edit') {
    updateModalOptions({
      title: '修改检查项'
    });
  } else {
    updateModalOptions({
      title: '新增检查项'
    });
  }
  currentRow.value = row;
  handleCheckItemShow();
}

function search() {
  getRightData();
}

function reset() {
  searchParams.value = {
    delFlag: null
  };
  search();
}
</script>

<template>
  <div class="form-setup-page min-h-500px flex gap-16px overflow-hidden p-8px pl-15px lt-sm:overflow-auto">
    <div class="left-tree h-full">
      <div class="title">
        <span class="text">点检表</span>
      </div>
      <div class="head-container">
        <AInput v-model:value="formName" placeholder="请输入点检表名称" />
      </div>
      <div class="head-tree">
        <ElTree
          ref="treeRef"
          :data="leftData"
          :props="defaultProps"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          node-key="id"
          default-expand-all
          highlight-current
          empty-text="暂无点检表"
          @node-click="handleNodeClick"
        >
          <template #default="{ data }">
            <div class="tree-node align-center w-full flex justify-between" :title="data.label">
              <div class="left align-center flex">
                <span
                  class="iconfont mr-5px"
                  :class="data.type === 'process' ? 'icon-gongxu gongxu-icon' : 'icon-jilubiao color-blue'"
                ></span>
                <span class="tree-label" :class="data.delFlag == '1' ? 'color-red' : ''">{{ data.label }}</span>
              </div>
              <div
                v-if="data.type === 'form'"
                v-hasAuth="['check-inventory-manage:form-setup:tree-edit']"
                class="right mr-15px"
              >
                <icon-ic-round-edit
                  class="align-sub text-size-16px color-blue"
                  @click="handleTreeItemEdit($event, data)"
                />
              </div>
            </div>
          </template>
        </ElTree>
      </div>
    </div>
    <div class="right-table ml-8px h-full flex-col-stretch gap-16px overflow-hidden">
      <CommonSearch
        v-model:searchParams="searchParams"
        :form-list="searchFormList"
        @reset="reset"
        @search="search"
      ></CommonSearch>
      <Table
        ref="tableRef"
        v-model:searchParams="searchParams"
        :column="column"
        :data-source="tableData"
        :show-row-selection="false"
        :scroll="{ y: 'auto' }"
        is-init-get-data
        :loading="loading"
      >
        <template #title>
          <AButton
            v-if="currentFormId"
            v-hasAuth="['check-inventory-manage:form-setup:add-check-item']"
            type="primary"
            size="small"
            ghost
            class="mini-btn mr-8px"
            @click="handleCheckItemEdit('add')"
          >
            <template #icon>
              <icon-ic-round-add class="align-sub text-icon" />
            </template>
            <span class="ml-3px">新增检查项</span>
          </AButton>
        </template>
      </Table>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.left-tree {
  width: 330px;
  padding: 8px;
  background: #fff;
  box-shadow: 2px 5px 8px 0 #eee;
  .title {
    text-align: center;
    color: #646cff;
    font-size: 18px;
    font-weight: bold;
    padding: 5px;
    .text {
      border-bottom: 2px solid #646cff;
      padding: 0 8px;
    }
  }
  .head-tree {
    height: calc(100% - 75px);
    overflow: auto;
  }
  .gongxu-icon {
    font-size: 13px !important;
    color: #646cff;
  }
  .align-center {
    align-items: center;
  }
  :deep(.el-tree) {
    .el-tree-node__content,
    .tree-node {
      width: 100%;
      .left {
        width: calc(100% - 40px);
        .tree-label {
          display: inline-block;
          width: calc(100% - 21px);
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
  }
}
.right-table {
  width: calc(100% - 330px);
}
</style>
